package com.newlink.building.secret.ui


import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.RadioGroup
import android.widget.TextView
import androidx.core.view.isGone
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.newlink.building.common_base.base.BaseApplication
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_DeviceType
import com.newlink.building.common_base.constant.Base_DoorKeyRepeatType
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.*
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.EnhancedLogger
import com.newlink.building.common_base.widget.CustomInputDialog
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.secret.R
import com.newlink.building.secret.adapter.Module_Secret_AreaSelectionAdapter
import com.newlink.building.secret.adapter.Module_Secret_DayOfMonthAdapter
import com.newlink.building.secret.adapter.Module_Secret_DayOfWeekAdapter
import com.newlink.building.secret.bean.Module_Secret_CheckBean
import com.newlink.building.secret.bean.Module_Secret_MutipleSelectBean
import com.newlink.building.secret.databinding.ActivityAddSecretkeyBinding
import com.newlink.building.secret.fragment.Module_Secret_TempSecretFragment
import com.newlink.building.secret.mvp.contract.Module_Secret_SecretKeyAddContract
import com.newlink.building.secret.mvp.presenter.Module_Secret_SecretKeyAddPresenter
import com.newlink.building.secret.widget.Module_Secret_DateChooseWheelViewDialog


/**
 * Created by xiaodong on 2022/9/23.
 */
class Module_Secret_SecretKeyAddActivityNL :
    NL_BaseMvpActivity<Module_Secret_SecretKeyAddContract.View, Module_Secret_SecretKeyAddContract.Presenter>(),
    Module_Secret_SecretKeyAddContract.View, View.OnClickListener {

    companion object {
        private const val TYPE_AREA = 0
        private const val TYPE_REPEAT = 1
    }

    private var deviceBeans = arrayListOf<Module_Secret_CheckBean>()

    private var repeatBeans = arrayListOf<Module_Secret_CheckBean>()

    private var weekBeans = arrayListOf<Module_Secret_MutipleSelectBean>()

    private var dayBeans = arrayListOf<Module_Secret_MutipleSelectBean>()

    private var selectedDeviceMacs = arrayListOf<String>()

    private var selectedRepeatType = 0

    private var selectCheckBean: Module_Secret_CheckBean? = null

    private val dayOfMonthAdapter: Module_Secret_DayOfMonthAdapter by lazy {
        Module_Secret_DayOfMonthAdapter(dayBeans)
    }
    private val dayOfWeekAdapter: Module_Secret_DayOfWeekAdapter by lazy {
        Module_Secret_DayOfWeekAdapter(weekBeans)
    }

    private val mDialog by lazy {
        DialogUtil.getWaitDialog(this)
    }

    //    override fun attachLayoutRes(): Int = R.layout.activity_add_secretkey
    private lateinit var mBinding: ActivityAddSecretkeyBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityAddSecretkeyBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun showLoading() {
        mDialog.setCancelable(false)
        if (!mDialog.isShowing) {
            mDialog.show()
        }
    }

    override fun hideLoading() {
        mDialog.dismiss()
    }

    override fun initData() {
        val periodArray = resources.getStringArray(R.array.secretkey_array_repetition_period)
        val weekArray = resources.getStringArray(R.array.secretkey_array_period_week)
        val weekIds = resources.getStringArray(R.array.secretkey_array_period_week_id)
        periodArray.forEachIndexed { index, s ->
            repeatBeans.add(Module_Secret_CheckBean(s, (index + 1).toString(), TYPE_REPEAT, false))
        }
        weekArray.forEachIndexed { index, s ->
            weekBeans.add(Module_Secret_MutipleSelectBean(s, weekIds[index], false))
        }
        for (index in 1..31) {
            dayBeans.add(Module_Secret_MutipleSelectBean(index.toString(), index.toString(), false))
        }
    }

    override fun initView() {
        super.initView()
        findViewById<TextView>(R.id.tv_title_common).text =
            resources.getString(R.string.title_add_secretkey)
        mBinding.recyclerViewRepeat.addItemDecoration(SpaceItemDecoration(this))
        mBinding.rlName.setOnClickListener(this)
        mBinding.rlFrequency.setOnClickListener(this)
        mBinding.rlLocation.setOnClickListener(this)
        mBinding.rlStartdateCustom.setOnClickListener(this)
        mBinding.rlEnddateCustom.setOnClickListener(this)
        mBinding.starttimeCustomValue.setOnClickListener(this)
        mBinding.endtimeCustomValue.setOnClickListener(this)
        mBinding.rlRepeat.setOnClickListener(this)
        mBinding.rlStarttimeNormal.setOnClickListener(this)
        mBinding.rlEndtimeNormal.setOnClickListener(this)
        findViewById<ImageView>(R.id.image_back).setOnClickListener(this)
        mBinding.btnAdd.setOnClickListener(this)

        dayOfMonthAdapter.setOnItemChildClickListener { adapter, _, position ->
            dayBeans[position].isChecked = !dayBeans[position].isChecked
            adapter.notifyDataSetChanged()
        }
        dayOfWeekAdapter.setOnItemChildClickListener { adapter, _, position ->
            weekBeans[position].isChecked = !weekBeans[position].isChecked
            adapter.notifyDataSetChanged()
        }

        mBinding.rgFrequency.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_frequency_infinite ->
                    mBinding.rlFrequency.isGone = true

                R.id.rb_frequency_custom ->
                    mBinding.rlFrequency.isGone = false
            }
        })

    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.image_back -> finish()
            R.id.btn_add -> {
                val name = mBinding.nameValue.text.toString()
                val openNum =
                    if (mBinding.rlFrequency.isGone) "-1" else mBinding.frequencyValue.text.toString()


                val startTimeNormal = mBinding.starttimeNormalValue.text.toString()
                val endTimeNormal = mBinding.endtimeNormalValue.text.toString()

                val startDateCustom = mBinding.startdateCustomValue.text.toString()
                val endDateCustom = mBinding.enddateCustomValue.text.toString()
                val startTimeCustom = mBinding.starttimeCustomValue.text.toString()
                val endTimeCustom = mBinding.endtimeCustomValue.text.toString()

                //有效区需要根据重复周期类型拼接
                var period = if (selectedRepeatType == Base_DoorKeyRepeatType.NoRepeat.type) {
                    "$startTimeNormal - $endTimeNormal"
                } else {
                    "$startDateCustom $startTimeCustom - $endDateCustom $endTimeCustom"
                }

                val repeat = mBinding.repeatValue.text.toString()

                val selectDaysOfWeek = getSelectDaysOfWeek()
                val selectDaysOfMonth = getSelectDaysOfMonth()
                var effectTime = when (selectedRepeatType) {
                    Base_DoorKeyRepeatType.WEEKLY.type -> selectDaysOfWeek
                    Base_DoorKeyRepeatType.MONTHLY.type -> selectDaysOfMonth
                    else -> arrayListOf()
                }

                if (TextUtils.isEmpty(name)) {
                    showToast(getString(R.string.secretkey_name_cannot_empty))
                    return
                }
                if (TextUtils.isEmpty(openNum)) {
                    showToast(getString(R.string.secretkey_frequency_cannot_empty))
                    return
                } else if (!TextUtils.equals(openNum, "-1")) {
                    if (openNum.toInt() < 1 || openNum.toInt() > 10000) {
                        showToast(getString(R.string.secretkey_frequency_cannot_range))
                        return
                    }
                }
                if (selectedDeviceMacs.size == 0) {
                    showToast(getString(R.string.secretkey_location_cannot_empty))
                    return
                }
                if (TextUtils.isEmpty(repeat)) {
                    showToast(getString(R.string.secretkey_repeat_cannot_empty))
                    return
                }
                if (selectedRepeatType == Base_DoorKeyRepeatType.WEEKLY.type && selectDaysOfWeek.size == 0) {
                    showToast(getString(R.string.secretkey_week_repeat_cannot_empty))
                    return
                }
                if (selectedRepeatType == Base_DoorKeyRepeatType.MONTHLY.type && selectDaysOfMonth.size == 0) {
                    showToast(getString(R.string.secretkey_month_repeat_cannot_empty))
                    return
                }
                if (selectedRepeatType == Base_DoorKeyRepeatType.NoRepeat.type) {
                    if (TextUtils.isEmpty(startTimeNormal)) {
                        showToast(getString(R.string.secretkey_start_time_cannot_empty))
                        return
                    }
                    if (TextUtils.isEmpty(endTimeNormal)) {
                        showToast(getString(R.string.secretkey_end_time_cannot_empty))
                        return
                    }
                } else {
                    if (TextUtils.isEmpty(startDateCustom)) {
                        showToast(getString(R.string.secretkey_start_date_cannot_empty))
                        return
                    }
                    if (TextUtils.isEmpty(endDateCustom)) {
                        showToast(getString(R.string.secretkey_end_date_cannot_empty))
                        return
                    }
                    if (TextUtils.isEmpty(startTimeCustom)) {
                        showToast(getString(R.string.secretkey_start_time_cannot_empty))
                        return
                    }
                    if (TextUtils.isEmpty(endTimeCustom)) {
                        showToast(getString(R.string.secretkey_end_time_cannot_empty))
                        return
                    }
                }

                EnhancedLogger.d(
                    "SecretKeyAddActivity",
                    "name:$name  openNum:${openNum.toInt()} period:$period  repeatType:$selectedRepeatType  macs:$selectedDeviceMacs  selectDaysOfWeek:$selectDaysOfWeek   selectDaysOfMonth:$selectDaysOfMonth"
                )

                mPresenter?.addSecretKey(
                    SecretKeyAddRequest(
                        accessToken = accessToken,
                        name = name,
                        prjType = 2,
                        openNum = openNum.toInt(),
                        repeatType = selectedRepeatType,
                        effectTime = effectTime,
                        period = period,
                        deviceMacs = selectedDeviceMacs
                    )
                )
            }

            R.id.rl_name -> showCustomInputDialog(
                resources.getString(R.string.secretkey_name),
                mBinding.nameValue.text.toString(),
                CustomInputDialog.TYPE_SECRETKEY_NAME,
                maxLength = 50
            )

            R.id.rl_frequency -> showCustomInputDialog(
                resources.getString(R.string.secretkey_frequency),
                mBinding.frequencyValue.text.toString(),
                CustomInputDialog.TYPE_SECRETKEY_FREQUENCY,
                EditorInfo.TYPE_CLASS_NUMBER,
                maxNumberValue = 10000
            )

            R.id.rl_location -> {
                //从缓存里获取设备列表数据,不做新请求`-
                if (deviceBeans.size == 0) {
                    deviceBeans = findDoorPhoneBeans()
//                    mPresenter?.getDeviceList(DeviceListRequest(accessToken,userId.toString(), KcpRquestType.TYPE_DEVICE_LIST,
//                        DeviceListRequestBody("",1, Int.MAX_VALUE)))
                }
                showBottomSheetDialog(this, deviceBeans, TYPE_AREA)
            }

            R.id.rl_starttime_normal -> {
                val startDateChooseDialog =
                    Module_Secret_DateChooseWheelViewDialog(
                        this
                    ) { time, _ ->
                        mBinding.starttimeNormalValue.text = time
                    }
                startDateChooseDialog.setDateDialogTitle(resources.getString(R.string.secretkey_starttime))
                startDateChooseDialog.setStyle(Module_Secret_DateChooseWheelViewDialog.Style.DETAULT)
                startDateChooseDialog.showDateChooseDialog()
            }

            R.id.rl_endtime_normal -> {
                val startDateChooseDialog =
                    Module_Secret_DateChooseWheelViewDialog(
                        this
                    ) { time, _ ->
                        mBinding.endtimeNormalValue.text = time
                    }
                startDateChooseDialog.setDateDialogTitle(resources.getString(R.string.secretkey_endtime))
                startDateChooseDialog.setStyle(Module_Secret_DateChooseWheelViewDialog.Style.DETAULT)
                startDateChooseDialog.showDateChooseDialog()
            }

            R.id.rl_startdate_custom -> {
                val startDateChooseDialog =
                    Module_Secret_DateChooseWheelViewDialog(
                        this
                    ) { time, _ ->
                        mBinding.startdateCustomValue.text = time
                    }
                startDateChooseDialog.setDateDialogTitle(resources.getString(R.string.secretkey_startdate))
                startDateChooseDialog.setStyle(Module_Secret_DateChooseWheelViewDialog.Style.DATE_ONLY)
                startDateChooseDialog.showDateChooseDialog()
            }

            R.id.rl_enddate_custom -> {
                val startDateChooseDialog =
                    Module_Secret_DateChooseWheelViewDialog(
                        this
                    ) { time, _ ->
                        mBinding.enddateCustomValue.text = time
                    }
                startDateChooseDialog.setDateDialogTitle(resources.getString(R.string.secretkey_enddate))
                startDateChooseDialog.setStyle(Module_Secret_DateChooseWheelViewDialog.Style.DATE_ONLY)
                startDateChooseDialog.showDateChooseDialog()
            }

            R.id.starttime_custom_value -> {
                val startDateChooseDialog =
                    Module_Secret_DateChooseWheelViewDialog(
                        this
                    ) { time, _ ->
                        mBinding.starttimeCustomValue.text = time
                    }
                startDateChooseDialog.setDateDialogTitle(resources.getString(R.string.secretkey_starttime))
                startDateChooseDialog.setStyle(Module_Secret_DateChooseWheelViewDialog.Style.TIME_ONLY)
                startDateChooseDialog.showDateChooseDialog()
            }

            R.id.endtime_custom_value -> {
                val startDateChooseDialog =
                    Module_Secret_DateChooseWheelViewDialog(
                        this
                    ) { time, _ ->
                        mBinding.endtimeCustomValue.text = time
                    }
                startDateChooseDialog.setDateDialogTitle(resources.getString(R.string.secretkey_endtime))
                startDateChooseDialog.setStyle(Module_Secret_DateChooseWheelViewDialog.Style.TIME_ONLY)
                startDateChooseDialog.showDateChooseDialog()
            }

            R.id.rl_repeat -> {
                showBottomSheetDialog(this, repeatBeans, TYPE_REPEAT)
            }
        }
    }

    private fun cleanWeekBeans() {
        for (item in weekBeans) {
            item.isChecked = false
        }
    }

    private fun cleanDayBeans() {
        for (item in dayBeans) {
            item.isChecked = false
        }
    }

//    private fun getSelectDaysOfWeek(): String {
//        val sb = StringBuilder()
//        for (item in weekBeans) {
//            if (item.isChecked) {
//                sb.append(item.value).append(",")
//            }
//        }
//        if (sb.length > 1) {
//            sb.deleteCharAt(sb.length - 1)
//        }
//        return sb.toString()
//    }

//    private fun getSelectDaysOfMonth(): String {
//        val sb = StringBuilder()
//        for (item in dayBeans) {
//            if (item.isChecked) {
//                sb.append(item.value).append(",")
//            }
//        }
//        if (sb.length > 1) {
//            sb.deleteCharAt(sb.length - 1)
//        }
//        return sb.toString()
//    }

    private fun getSelectDaysOfWeek(): MutableList<Int> {
        val list = arrayListOf<Int>()
        for (item in weekBeans) {
            if (item.isChecked) {
                list.add(item.value.toInt())
            }
        }
        return list
    }

    private fun getSelectDaysOfMonth(): MutableList<Int> {
        val list = arrayListOf<Int>()
        for (item in dayBeans) {
            if (item.isChecked) {
                list.add(item.value.toInt())
            }
        }
        return list
    }

    private fun showCustomInputDialog(
        tittle: String,
        value: String,
        type: Int,
        inputType: Int = EditorInfo.TYPE_CLASS_TEXT,
        maxLength: Int? = null,
        maxNumberValue: Int? = null,
    ) {
        val customInputDialog = CustomInputDialog(this)
        customInputDialog.setTitle(tittle).setText(value).setType(type).setInputType(inputType)
            .setMaxLength(maxLength).setMaxNumberValue(maxNumberValue)
            .setNegativeButton(listener = object : CustomInputDialog.OnClickListener {
                override fun onClick(type: Int, inputText: String) {
                    customInputDialog.dismiss()
                }

            }).setPositiveButton(listener = object : CustomInputDialog.OnClickListener {
                override fun onClick(type: Int, inputText: String) {
                    if (type == CustomInputDialog.TYPE_SECRETKEY_NAME) {
                        mBinding.nameValue.text = inputText
                    } else if (type == CustomInputDialog.TYPE_SECRETKEY_FREQUENCY) {
                        mBinding.frequencyValue.text = inputText
                    }

                    customInputDialog.dismiss()
                }

            })
        customInputDialog.show()
    }

    private fun showBottomSheetDialog(context: Context, cbs: MutableList<Module_Secret_CheckBean>, type: Int) {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
        bottomSheetDialog.setCanceledOnTouchOutside(false)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_secretkey_area, null, false)
        val recyclerView = view.findViewById(R.id.recyclerView) as RecyclerView
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            //点取消后清除标记,再点击根据显示的名字重置标记
            for (item in cbs) {
                item.isChecked = false
            }
            bottomSheetDialog.dismiss()
        }

        val title = view.findViewById<TextView>(R.id.tv_title)
        when (type) {
            TYPE_AREA -> {
                title.text = resources.getString(R.string.secretkey_location)
                //可能选择多个设备
                for (value in selectedDeviceMacs) {
                    for (item in cbs) {
                        if (item.value == value) {
                            item.isChecked = true
                        }
                    }
                }
            }

            TYPE_REPEAT -> {
                title.text = resources.getString(R.string.secretkey_weekly)
                val selecValue = mBinding.repeatValue.text
                for (item in cbs) {
                    if (item.name == selecValue) {
                        item.isChecked = true
                    }
                }
            }
        }
        view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            val sb = StringBuilder()
            when (type) {
                TYPE_AREA -> {
                    selectedDeviceMacs.clear()
                    for (item in cbs) {
                        if (item.isChecked) {
                            selectedDeviceMacs.add(item.value)
                            var tempName = item.name
                            if (item.name.length > 16) {
                                tempName = tempName.substring(0, 15).plus("...")
                            }
                            sb.append(tempName).append("/")
                        }
                    }
                    if (sb.length > 1) {
                        sb.deleteCharAt(sb.length - 1)
                    }
                    mBinding.locationValue.text = sb.toString()
                }

                TYPE_REPEAT -> {
                    for (item in cbs) {
                        if (item.isChecked) {
                            selectedRepeatType = item.value.toInt()
                            selectCheckBean = item
                            sb.append(item.name).append("、")
                        }
                    }
                    updateTimePickerView()
                    if (sb.length > 1) {
                        sb.deleteCharAt(sb.length - 1)
                    }
                    mBinding.repeatValue.text = sb.toString()
                    if (selectCheckBean?.value == Base_DoorKeyRepeatType.WEEKLY.type.toString()) {
                        displayDayOfWeekAdapter()
                    } else if (selectCheckBean?.value == Base_DoorKeyRepeatType.MONTHLY.type.toString()) {
                        displayDayOfMonthAdapter()
                    } else {
                        displayNone()
                    }
                }
            }
            bottomSheetDialog.dismiss()
        }
        val mAdapter = Module_Secret_AreaSelectionAdapter(cbs)
        recyclerView.adapter = mAdapter
        recyclerView.addItemDecoration(SpaceItemDecoration(context))
        mAdapter.setOnItemClickListener { adapter, _, position ->

            selectCheckBean = cbs[position]
            when (type) {
                TYPE_AREA -> {
                    cbs[position].isChecked = !cbs[position].isChecked
                }

                TYPE_REPEAT -> {
                    for ((index, item) in cbs.withIndex()) {
                        item.isChecked = index == position
                    }
                }
            }

            adapter.notifyDataSetChanged()
        }

        bottomSheetDialog.setContentView(view)
        bottomSheetDialog.show()
    }

    fun updateTimePickerView() {
        if (selectedRepeatType == Base_DoorKeyRepeatType.NoRepeat.type) {
            mBinding.containerRepeatNormal.visibility = View.VISIBLE
            mBinding.containerRepeatCustom.visibility = View.GONE
        } else {
            mBinding.containerRepeatNormal.visibility = View.GONE
            mBinding.containerRepeatCustom.visibility = View.VISIBLE
        }
        mBinding.starttimeNormalValue.text = ""
        mBinding.endtimeNormalValue.text = ""
        mBinding.startdateCustomValue.text = ""
        mBinding.enddateCustomValue.text = ""
        mBinding.starttimeCustomValue.text = ""
        mBinding.endtimeCustomValue.text = ""
    }

    override fun createPresenter(): Module_Secret_SecretKeyAddContract.Presenter = Module_Secret_SecretKeyAddPresenter()

    override fun refreshAddStatus(data: StatusData) {
        if (data.flag) {
            setResult(Module_Secret_TempSecretFragment.RESULT_CODE)
            finish()
        }
        val message =
            if (data.flag) getString(R.string.secretkey_add_success) else getString(R.string.secretkey_add_failed)
        showToast(message)
    }

    override fun refreshDeviceList(data: MutableList<DeviceData>) {
        deviceBeans.clear()
        for (item in data) {
            deviceBeans.add(Module_Secret_CheckBean(item.devName.orEmpty(), item.mac, TYPE_AREA, false))
        }
        showBottomSheetDialog(this, deviceBeans, TYPE_AREA)
    }

    private fun displayDayOfMonthAdapter() {
        cleanWeekBeans()
        mBinding.recyclerViewRepeat.visibility = View.VISIBLE
        mBinding.recyclerViewRepeat.layoutManager = GridLayoutManager(this, 7)
        mBinding.recyclerViewRepeat.adapter = dayOfMonthAdapter
    }

    private fun displayDayOfWeekAdapter() {
        cleanDayBeans()
        mBinding.recyclerViewRepeat.visibility = View.VISIBLE
        mBinding.recyclerViewRepeat.layoutManager = GridLayoutManager(this, 2)
        mBinding.recyclerViewRepeat.adapter = dayOfWeekAdapter
    }

    private fun displayNone() {
        cleanWeekBeans()
        cleanDayBeans()
        mBinding.recyclerViewRepeat.visibility = View.GONE
    }

    private fun findDoorPhoneBeans(): ArrayList<Module_Secret_CheckBean> {
        val doorPhoneBeans: ArrayList<Module_Secret_CheckBean> = arrayListOf()

        for (item in BaseApplication.cacheDeviceDatas) {
            if (item.devType == Base_DeviceType.DOORPHONE.code) {
                doorPhoneBeans.add(Module_Secret_CheckBean(item.devName.orEmpty(), item.mac, TYPE_AREA, false))
            }
        }
        return doorPhoneBeans
    }
}